<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Screen</title>
</head>

<body>
  <h1>Show my screen</h1>

  <video autoplay id="screen-view" width="50%"></video>
  <button id="get-screen" style="display:none">Get the screen</button>
  <button id="stop-screen" style="display:none">Stop the screen</button>

  <script>
    (() => {
      const EXTENSION_ID = 'YOUR_EXTENSION_ID_HERE';

      chrome.runtime.sendMessage(EXTENSION_ID, 'version', response => {
        if (!response) {
          console.log('No extension');
          return;
        }
        console.log('Extension version: ', response.version);
        const video = document.getElementById('screen-view');
        const getScreen = document.getElementById('get-screen');
        const stopScreen = document.getElementById('stop-screen');
        const request = { sources: ['window', 'screen', 'tab'] };
        let stream;

        getScreen.style.display = 'inline';
        getScreen.addEventListener('click', event => {
          chrome.runtime.sendMessage(EXTENSION_ID, request, response => {
            if (response && response.type === 'success') {
              navigator.mediaDevices
                .getUserMedia({
                  video: {
                    mandatory: {
                      chromeMediaSource: 'desktop',
                      chromeMediaSourceId: response.streamId
                    }
                  }
                })
                .then(returnedStream => {
                  stream = returnedStream;
                  video.src = URL.createObjectURL(stream);
                  getScreen.style.display = 'none';
                  stopScreen.style.display = 'inline';
                })
                .catch(err => {
                  console.error('Could not get stream: ', err);
                });
            } else {
              console.error('Could not get stream');
            }
          });
        });

        stopScreen.addEventListener('click', event => {
          stream.getTracks().forEach(track => track.stop());
          video.src = '';
          stopScreen.style.display = 'none';
          getScreen.style.display = 'inline';
        });
      });
    })();
  </script>
</body>

</html>